﻿#nullable enable
using System;
using Microsoft.EntityFrameworkCore;
using REP.Domain.Entities;

namespace ERP.Infeartructure
{
    /// <summary>
    /// EF Core 数据上下文
    /// </summary>
    public class ErpDbContext : DbContext
    {
        public ErpDbContext(DbContextOptions<ErpDbContext> options) : base(options) { }

        // DbSet
        public DbSet<Bom>? Boms { get; set; }
        public DbSet<BomAccessory>? BomAccessories { get; set; }
        public DbSet<MaterialItem>? MaterialItems { get; set; }
        public DbSet<ProcessRoute>? ProcessRoutes { get; set; }
        public DbSet<ProcessStep>? ProcessSteps { get; set; }
        public DbSet<BomProcessRoute>? BomProcessRoutes { get; set; }
        public DbSet<Attachment>? Attachments { get; set; }
        public DbSet<OperationLog>? OperationLogs { get; set; }
        public DbSet<User>? Users { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // 表名（可按需要调整前缀）
            modelBuilder.Entity<Bom>().ToTable("Bom");
            modelBuilder.Entity<BomAccessory>().ToTable("BomAccessory");
            modelBuilder.Entity<MaterialItem>().ToTable("MaterialItem");
            modelBuilder.Entity<ProcessRoute>().ToTable("ProcessRoute");
            modelBuilder.Entity<ProcessStep>().ToTable("ProcessStep");
            modelBuilder.Entity<BomProcessRoute>().ToTable("BomProcessRoute");
            modelBuilder.Entity<Attachment>().ToTable("Attachment");
            modelBuilder.Entity<OperationLog>().ToTable("OperationLog");
            modelBuilder.Entity<User>().ToTable("User");

            // 主键（若使用 Guid?，此处不强制 ValueGeneratedOnAdd，交由应用赋值）
            modelBuilder.Entity<BaseEntity>();

            // 精度配置：价格、库存、工时
            modelBuilder.Entity<BomAccessory>()
                .Property(p => p.PurchasePrice).HasPrecision(18, 4);
            modelBuilder.Entity<BomAccessory>()
                .Property(p => p.SalesPrice).HasPrecision(18, 4);
            modelBuilder.Entity<BomAccessory>()
                .Property(p => p.TotalStock).HasPrecision(18, 4);
            modelBuilder.Entity<BomAccessory>()
                .Property(p => p.Qty).HasPrecision(18, 4);

            modelBuilder.Entity<MaterialItem>()
                .Property(p => p.PurchasePrice).HasPrecision(18, 4);
            modelBuilder.Entity<MaterialItem>()
                .Property(p => p.SalesPrice).HasPrecision(18, 4);
            modelBuilder.Entity<MaterialItem>()
                .Property(p => p.TotalStock).HasPrecision(18, 4);

            modelBuilder.Entity<ProcessRoute>()
                .Property(p => p.StdTotalHours).HasPrecision(18, 4);
            modelBuilder.Entity<ProcessStep>()
                .Property(p => p.StdHours).HasPrecision(18, 4);

            // 关系：BOM - 配件（一对多）
            modelBuilder.Entity<BomAccessory>()
                .HasOne<Bom>()
                .WithMany(b => b.Accessories)
                .HasForeignKey(p => p.BomId)
                .OnDelete(DeleteBehavior.Cascade);

            // 关系：BOM - 附件（一对多）
            modelBuilder.Entity<Attachment>()
                .HasOne<Bom>()
                .WithMany()
                .HasForeignKey(a => a.BomId)
                .OnDelete(DeleteBehavior.Cascade);

            // 关系：BOM - 操作记录（一对多）
            modelBuilder.Entity<OperationLog>()
                .HasOne<Bom>()
                .WithMany()
                .HasForeignKey(l => l.BomId)
                .OnDelete(DeleteBehavior.Cascade);

            // 关系：路线 - 步骤（一对多）
            modelBuilder.Entity<ProcessStep>()
                .HasOne<ProcessRoute>()
                .WithMany(r => r.Steps)
                .HasForeignKey(s => s.RouteId)
                .OnDelete(DeleteBehavior.Cascade);

            // 关系：BOM - 路线（多对多，显式映射表）
            modelBuilder.Entity<BomProcessRoute>()
                .HasOne<Bom>()
                .WithMany(b => b.ProcessRoutes)
                .HasForeignKey(br => br.BomId)
                .OnDelete(DeleteBehavior.Cascade);

            modelBuilder.Entity<BomProcessRoute>()
                .HasOne<ProcessRoute>()
                .WithMany()
                .HasForeignKey(br => br.RouteId)
                .OnDelete(DeleteBehavior.Cascade);

            // 用户种子数据（开发用）
            modelBuilder.Entity<User>().HasData(new User
            {
                Id = Guid.Parse("00000000-0000-0000-0000-000000000001"),
                UserName = "admin",
                RealName = "管理员",
                Password = "123456",
                Enabled = true,
                CreatedBy = "system",
                CreatedAt = DateTime.UtcNow
            });
        }
    }
}
